<template>
  <div>
    <table
      border="1"
      width="700"
      style="border-collapse: collapse"
    >
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" v-model="chkAll" /> <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- 使用组件，父子传值，自定义属性 -->
        <tr-com v-for="(obj, index) in goodList" :key="index" :obj="obj" @delCart="delCart(index)"></tr-com>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">
            {{total}}
          </td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
// 导入组件
import trCom from './components/tr-com.vue'
export default {
  // 注册组件
  components: { trCom },
  data () {
    return {
      goodList: [
        {
          name: '诸葛亮',
          price: 1000,
          num: 1,
          checked: false
        },
        {
          name: '蔡文姬',
          price: 1500,
          num: 1,
          checked: false
        },
        {
          name: '妲己',
          price: 2000,
          num: 1,
          checked: false
        },
        {
          name: '鲁班',
          price: 2200,
          num: 1,
          checked: false
        }
      ]
    }
  },
  // 计算属性
  computed: {
    // 计算总额
    total () {
      return this.goodList.filter(el => el.checked).reduce((p, n) => p + n.num * n.price, 0)
    },
    // 全选全不选
    chkAll: {
      get () {
        return this.goodList.every(el => el.checked)
      },
      set (value) {
        this.goodList.map(el => (el.checked = value))
      }
    }
  },
  methods: {
    delCart (index) {
      this.goodList.splice(index, 1)
    }
  }
}
</script>

<style>
</style>
